<template>
  <!-- 模态框 -->
  <div class="model">
    <!-- 遮罩层 -->
    <div class="mask" @click="chengeIsShowLoginModal(false)"></div>
    <!-- 登陆组件 -->
    <div class="loginbox">
      <div class="close" @click="chengeIsShowLoginModal(false)"></div>
      <!-- tab导航切换 -->
      <section class="navs">
        <a
          href="javascript:;"
          :class="{ acvite: showLogin == true }"
          @click="showLogin = true"
          >手机号登陆</a
        >
        |
        <a
          href="javascript:;"
          :class="{ acvite: showLogin == false }"
          @click="showQrwx"
          >二维码登陆</a
        >
      </section>

      <div class="content">
        <!-- 手机号登陆 -->
        <div class="phonelogin" v-show="showLogin">
          <div class="row">
            <input
              type="text"
              placeholder="请输入手机号"
              class="ipt"
              v-model="phoenNumber"
            />
          </div>

          <div class="row">
            <!-- <slide-verify
              :l="42"
              :r="20"
              :w="362"
              :h="140"
              @success="onSuccess"
              @fail="onFail"
              @refresh="onRefresh"
              :style="{ width: '100%' }"
              class="slide-box"
              ref="slideBlock"
              :imgs="imgArr"
              :slider-text="msg"
            ></slide-verify> -->
          </div>

          <div class="row">
            <input
              type="text"
              placeholder="输入短信验证码"
              class="ipt"
              v-model="dxcode"
            />
            <button class="btn" @click="getCode" v-show="!isShowCount">
              获取验证码
            </button>
            <button class="btn" v-show="isShowCount">{{ count }}s</button>
          </div>

          <div class="row">
            <button class="btnrow" @click="subminFn">登陆</button>
          </div>
        </div>

        <!-- 二维码登陆 -->
        <div class="qrlogin" v-show="!showLogin" id="weixin">二维码登陆</div>
      </div>
    </div>
  </div>
</template>

<script>
// 1。在app。vue中显示登陆组件
import { mapMutations, mapActions } from "vuex";
import { validatePhomeNumber } from "@/utils";
import {
  SendSMSAPI,
  PhoneReginAPI,
  BindWxAPI,
  UserProfilesAPI,
} from "@/request/api";
export default {
  data() {
    return {
      showLogin: true, //是否显示导航切换
      msg: "向右滑动",
      imgArr: [
        require("../assets/img/integral-03.9870f3f1.png"),
        require("../assets/img/integral-04.afadcbdf.png"),
        require("../assets/img/integral-01.9386d4bf.png"),
      ],
      phoenNumber: "", //获取手机号
      isShowCount: false, //是否显示倒计时
      count: 6, //计数值
      dxcode: "", //短信验证码
    };
  },
  methods: {
    ...mapActions({
      asyncChangeIsShowToast: "showToast/asyncChangeIsShowToast",
      asyncChengeUserInfo: "userInfo/asyncChengeUserInfo",
    }),
    ...mapMutations({
      chengeIsShowLoginModal: "showModal/chengeIsShowLoginModal",
      changeIsLogined: "loginStatus/changeIsLogined",
      changeIsShowToast: "showToast/changeIsShowToast",
      chengeUserInfo: "userInfo/chengeUserInfo",
    }),


    //提取手机号和滑块验证码的公共函数
    toVerify() {
      //1．判断手机号不能为空
      if (!validatePhomeNumber(this.phoenNumber)) {
        // alert("请输入正确的的手机号码"); //这里用异步的
        this.asyncChangeIsShowToast({
          isshow: true,
          msg: "请输入正确的的手机号码",
          type: "danger",
        });
        return;
      }
      return true; //只要手机号和滑块都输入了，表示验证通过了。true o
    },

    // 获取验证码
    async getCode() {
      //业务逻辑
      //1．判断手机号不能为空
      //2．判断滑块验证码滑动正确
      let ret = this.toVerify();
      if (!ret) return;

      //3．获取验证码（调用后端接口）倒计时6os ,l
      let res = await SendSMSAPI({
        phone: this.phoenNumber,
      });
      console.log(res);
      //如果没有发送成功（失败），给与一个相应的提示。(不为0)
      if (!res) return;
      // 然后交给响应拦截器处理

      //如果没有发送成功 返回0
      if (res.code == 0) {
        this.isShowCount = true;
        let timer = setInterval(() => {
          this.count--;
          if (this.count == 0) {
            clearInterval(timer);
            this.count = 6;
            this.isShowCount = false;
          }
        }, 1000);
      }

      alert("登陆成功");
    },
    //登陆功能
    async subminFn() {
      //提取手机号和滑块验证码的公共函数
      if (!this.toVerify()) return; //代表提示 然后return掉

      //3．判断短信验证码是否输入正确如果不正确，提示，并且return(因为后台没有返回手机上收到的验证码的值，此处只是验证是否非空)
      if (this.dxcode.trim() == "") {
        // alert("短信不能为空");
        this.asyncChangeIsShowToast({
          isshow: true,
          msg: "短信不能为空",
          type: "danger",
        });
        return;
      }

      //4．发送登录请求(普通登录请求PhoneReginAPI关联微信的登录[uuid]BindwvXAPI)
      let uuid = localStorage.getItem("uuid");
      let res = null;
      if (uuid) {
        //关联微信登录
        res = await BindWxAPI({
          verifyCode: this.dxcode,
          phone: this.phoenNumber,
          uuid,
        });
        console.log("关联微信登录", res);
      } else {
        //普通登录
        res = await PhoneReginAPI({
          verifyCode: this.dxcode,
          phone: this.phoenNumber,
        });
        console.log("普通登录", res);
        if (!res) return; //如果函数返回值为nudefied 就retuen掉
        if (res.code == 0) {
          // 1.提示框
          // alert("登陆成功");
          this.asyncChangeIsShowToast({
            isshow: true,
            msg: "登陆成功",
            type: "success",
          });

          //  2 存tokin
          localStorage.setItem("x-auth-token", res["x-auth-token"]);
          // 3 隐藏登陆框
          this.chengeIsShowLoginModal(false);
          //4.topbar中登录按钮要变成购物车按钮。(登录状态)--一会写(先去准备购物车按钮样式)

          this.changeIsLogined(true); //再Login.vue 登录成功后 ，更新 登录状态isLogined。
          //5. uuid使用过后就没有用了，需要删除
          localStorage.removeItem("uuid");

          //6.登陆成功后 获取用户信息
          // 优化 ：不在这里请求数据 在vuex的异步中去请求
          // let user = await UserProfilesAPI();
          this.asyncChengeUserInfo(); //点击登录后调用actions里的这个方法
        }
      }
    },
    showQrwx() {
      this.showLogin = false;
      //
      let _this = this;
      new WxLogin({
        id: "weixin",
        appid: "wx67cfaf9e3ad31a0d", // 这个appid要填死
        scope: "snsapi_login",
        // 扫码成功后重定向的接口
        redirect_uri: "https://sc.wolfcode.cn/cms/wechatUsers/shop/PC",
        // state填写编码后的url
        state: encodeURIComponent(
          window.btoa("http://127.0.0.1:8080" + _this.$route.path)
        ),
        // 调用样式文件
        href: "data:text/css;base64,LmltcG93ZXJCb3ggLnRpdGxlLA0KLmltcG93ZXJCb3ggLmluZm8gew0KICBkaXNwbGF5OiBub25lOw0KfQ0KLmltcG93ZXJCb3ggcXJjb2RlIHsNCiAgbWFyZ2luLXRvcDogMjBweDsNCn0NCi53ZWJfcXJjb2RlX3R5cGVfaWZyYW1lIHsNCiAgcGFkZGluZy1sZWZ0OiAzNXB4Ow0KICB0ZXh0LWFsaWduOiBjZW50ZXI7DQp9DQo=",
      });
    },
  },
};
</script>

<style lang="less" scoped>
.model {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  .mask {
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
  }
  .loginbox {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    margin: auto;
    width: 555px;
    height: 423px;
    background: url(../assets/img/login-box-bg.png);
    .close {
      position: absolute;
      top: 10px;
      right: 60px;
      width: 22px;
      height: 22px;
      background: url(../assets/img/close.png);
    }
    .navs {
      padding-top: 40px;
      text-align: center;
      font-size: 18px;
      a {
        color: #000;
        text-decoration: none;
      }
      .acvite {
        color: red;
      }
    }
    .content {
      width: 355px;
      margin: 20px auto;

      .row {
        margin-bottom: 20px;
        display: flex;
        input {
          height: 40px;
          flex: 1;
          padding-left: 10px;
        }
        .btn {
          width: 100px;
          margin-left: 6px;
          background-color: #0a328e;
          color: #fff;
          line-height: 40px;
          display: flex;
          justify-content: center;
        }
        .btnrow {
          width: 100%;
          height: 50px;
          background-color: #0a328e;
          color: #fff;
        }
      }
    }
  }
}

/deep/.slide-box {
  width: 100%;
  position: relative;
  box-sizing: border-box;
  canvas {
    position: absolute;
    left: 0;
    top: -120px;
    display: none;
    width: 100%;
    box-sizing: border-box;
  }
  .slide-verify-block {
    width: 85px;
    height: 136px;
  }
  .slide-verify-refresh-icon {
    top: -120px;
    display: none;
  }
  &:hover {
    canvas {
      display: block;
    }
    .slide-verify-refresh-icon {
      display: block;
    }
  }
}
</style>